<template>
  <div class="createCloumn">


    <div class="create_columnIndex">
      <div class="columnIndex_button">
        <a-button class="addButton" type="primary" @click="router.go(-1)">
          返回
        </a-button>
      </div>

      <!-- 新建栏目模态框 -->
      <div class="creatForm">
        <a-form name="advanced_search" autoComplete="off" class="ant-advanced-search-form" :model="formState"
          ref="columnFrom">
          <a-form-item :label="formState.upOrg.label" :name="['upOrg', 'value']" :rules="[formState.upOrg.rule]">
            <a-tree-select class="AtreeSelect" placeholder="请选择" v-model:value="formState.upOrg.value"
              ref="usermanage_treeSelect" show-search :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
              allow-clear treeNodeFilterProp="channelName"
              :fieldNames="{ children: 'children', label: 'channelName', value: 'id' }" tree-default-expand-all
              :tree-data="upOrgOptions" @change="changeContent">
            </a-tree-select>

            <span v-if="isModelDisable && formState.upOrg.value" class="uporg-text">当前栏目下有内容，栏目模型会与上级栏目一致，且内容会移动至新建的栏目下；请先关闭采集设置再进行当前设置</span>
            <span v-if="!formState.upOrg.value" class="uporg-text">不选择上级栏目则创建的为一级栏目</span>
          </a-form-item>
          <a-form-item :label="formState.columnModel.label" :name="['columnModel', 'value']"
            :rules="[formState.columnModel.rule]">
            <a-select v-model:value="formState.columnModel.value" :disabled="isModelDisable" @change="changeModel"
              placeholder="请选择" :options="contentOptions" show-search></a-select>
          </a-form-item>
          <a-form-item v-if="!isCreate" :name="['columnName', 'value']" :label="formState.columnName.label"
            :rules="[formState.columnName.rule]">
            <a-input placeholder="请输入" v-model:value="formState.columnName.value" @keyup="formState.columnName.value=formState.columnName.value.replace(/\s+/g, '')" @blur="changeBlur" show-count
              :maxlength="25" allow-clear />
          </a-form-item>
          <a-form-item v-if="!isCreate" :name="['path', 'value']" :label="formState.path.label"
            :rules="[formState.path.rule]">
            <a-input placeholder="请输入" v-model:value="formState.path.value" />
          </a-form-item>
          <a-form-item v-if="formState.columnModel.value" :label="formState.PCModel.label">
            <a-select v-model:value="formState.PCModel.value" placeholder="请选择"
              :options="formState.PCModel.options"></a-select>
          </a-form-item>
          <a-form-item v-if="formState.columnModel.value" :label="formState.MobileModel.label">
            <a-select v-model:value="formState.MobileModel.value" placeholder="请选择"
              :options="formState.MobileModel.options"></a-select>
          </a-form-item>
          <a-form-item label="内容模型模板选择：">
            <div class="baseTable">
              <baseTable :columns="columns.addColumnModelColumns" :selectedRowKeys="rowSelectedKey" :hideSelectAll="1"
                :dataSource="contentModelList" :scroll="{ y: 200 }" ref="addModelBaseTables">
                <template #headerCell="{column}">
                  <template v-if="column.key === 'tplPc'">
                <div class="tpllPc">
                  <span class="title">{{ column.title }}</span>
              <a-tooltip placement="right">
                <template #title>
                  <span>内容模型绑定内容模板后可进行选择</span>
                </template>
                <span style="color: #1c6bec;" class="iconfont icon-hint"></span>
              </a-tooltip>
                <span class="tips">内容模型绑定内容模板后可进行选择</span>
                </div>
                </template>
                <template v-if="column.key === 'tplMobile'">
                  <div class="tpllPc">
                  <span class="title">{{ column.title }}</span>
              <a-tooltip placement="right">
                <template #title>
                  <span>内容模型绑定内容模板后可进行选择</span>
                </template>
                <span style="color: #1c6bec;" class="iconfont icon-hint"></span>
              </a-tooltip>
                <span class="tips">内容模型绑定内容模板后可进行选择</span>
                </div>
                </template>
                </template>
                <template #bodyCell="{ column, text, record }">
                  <template v-if="column.ellipsis">
                    <table-tool-tip :text="text" :column="column"></table-tool-tip>
                  </template>
                  <template v-if="column.dataIndex === 'tplPc'">
                    <a-select class="modal-select" v-model:value="record.tplPc" @focus="onFocus(record.id, 1)"
                      placeholder="请选择" :options="pcTplList"></a-select>
                  </template>
                  <template v-if="column.dataIndex === 'mobileTpl'">
                    <a-select class="modal-select" v-model:value="record.mobileTpl" @focus="onFocus(record.id, 1)"
                      placeholder="请选择" :options="mobileTplList"></a-select>
                  </template>
                </template>
              </baseTable>
            </div>
          </a-form-item>
        </a-form>
      </div>

    </div>
    <div class="table-bottom_fiexd" :style="styleWidth">
      <a-button type="primary" @click="buttonMessage">保存</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, watch, createVNode } from "vue";
import {
  scrollType,
  dataSourceType,
  detailDataType,
  configDataType,
  modeProp,
} from "@/type.d";
import request from "@/api/index";
import { useRouter } from "vue-router";
import columns from "@/components/table/tableConfig/columnsName";
import { Modal, message, TreeSelectProps } from "ant-design-vue";
import { getTableScroll } from "@/components/table/tableConfig/table";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { checkColumnName, checkPath } from "./formRuler";
import { randomWord } from "@/utils/common";
import baseTable from "@/components/table/baseTable.vue";
import iptRules from "@/utils/inputRule";
import { routerPerm } from "@/utils/common";
import { useFixeWidth, styleWidth } from '@/hooks/useFixeWidth';
import msgModal from "@/components/modal/modelConfig/MsGModal";
//router
const router: any = useRouter();
//data
const btnPerm = ref<any[]>([]);

//索引号管理集中数据
const columnFrom = ref<any>("columnFrom");
const upOrgOptions = ref<TreeSelectProps["treeData"]>([]);
const contentOptions = ref([]);
const isModelDisable = ref<boolean>(false);

//栏目新增-根据栏目id获取栏目内容是否存在和模型信息
const checkColumnContent = async () => {
  let param = { id: formState.value.parentId };
  const content = await request.fetchChannelContentModel(param);
  if (content.contentExists) {
    formState.value.modelId = content.modelId;
  }
};
const copyColumnData = ref<dataSourceType[]>([]);

const formState = ref<dataSourceType>({
  upOrg: {
    value: undefined,
    rule: {
      required: false,
      // validator: checkOrgContent,
      // msg1: '当前栏目下有内容，栏目模型会与上级栏目一致，且内容会移动至新建的栏目下；请先关闭采集设置再进行当前设置',
      // api: 'fetchChannelContentExist',
      trigger: [""],
    },
    msg: "",
    label: "上级栏目",
  },
  columnModel: {
    value: undefined,
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "栏目模型不能为空！",
    },
    label: "栏目模型",
  },
  columnName: {
    value: "",
    rule: {
      required: true,
      validator: checkColumnName,
      trigger: ["blur", "change"],
      msg1: "栏目名称不能为空！",
      msg2: "栏目名称已存在！",
      api: "channelNameCheck",
      params: { id: "" },
    },
    label: "栏目名称",
  },
  path: {
    value: "",
    rule: {
      required: true,
      trigger: ["blur"],
      validator: checkPath,
      api: "fetchUserSecretUnique",
    },
    label: "访问路径",
  },
  PCModel: {
    value: undefined,
    rule: {
      required: false,
      trigger: ["change", "blur"],
      message: "栏目模型不能为空！",
    },
    label: "栏目PC端模板",
    options: [],
  },
  MobileModel: {
    value: undefined,
    rule: {
      required: false,
      trigger: ["change", "blur"],
      message: "栏目模型不能为空！",
    },
    label: "栏目手机端模板",
    options: [],
  },
  parentId: "",
  modelId: "",
  id: "",
});
const isCreate = ref<boolean>(false); //判断是新加、编辑或者批量上传来复用模态框
// const dataList = ref(dataSource.value.slice(0, 10))

const isVisible = ref(false); //控制是否展示编辑对话框
// 选择内容模板
const rowSelectedKey = ref<dataSourceType[]>([]);
const contentModelList = ref<dataSourceType[]>([]); // 内容模板列表
const pcTplList = ref<dataSourceType[]>([]);
const mobileTplList = ref<dataSourceType[]>([]);
const addModelBaseTables = ref();
//methods
const loop = (data: dataSourceType[], id: any, value: any, type: string): any => {
  for (let i = 0; i < data.length; i++) {
    if (data[i].id == id) {
      type == "modify" ? (data[i].channelName = value) : ""; // 修改值
      type == "minus" ? data.splice(i, 1) : ""; //删除值
      if (type == "add") {
        let obj = {
          channelName: "",
          id: randomWord(false, 4, 4),
          children: [],
        };
        data[i].children.push(obj);
      }
    } else {
      if (data[i].children instanceof Array && data[i].children.length) {
        loop(data[i].children, id, value, type);
      }
    }
  }
};

//获取新增层级树列表
const fetchChannelChannelTree = async () => {
  let data = await request.fetchChannelChannelTree();
  nextTick(() => {
    copyColumnData.value = JSON.parse(JSON.stringify(data));
    upOrgOptions.value = JSON.parse(JSON.stringify(data));
    deepRec(upOrgOptions.value);
  });
};

//获取上级栏目id
const changeContent = async (e: string, options: any) => {
  formState.value.upOrg.value = e;
  formState.value.parentId = e;
  const res = await request.fetchChannelContentExist({ id: e });
  if (res.contentExists) {
    isModelDisable.value = true;
    formState.value.columnModel.value = getModelValue(res.modelId);
    formState.value.modelId = res.modelId;
  } else {
    isModelDisable.value = false;
  }
};

//栏目名称
const changeBlur = async (e: any) => {
  let params: dataSourceType = {
    text: e.target.value,
  };
  if (formState.value.path.value === "") {
    await request.fetchChiese2PY(params).then((res: dataSourceType) => {
      formState.value.path.value = formState.value.path.value || res;
    });
    ``;
  }
};
//获取栏目模型id
const changeModel = async (e: string, options: any) => {
  formState.value.columnModel.value = e;
  formState.value.modelId = options.id;
  const list = (await request.fetchChannelTplList({ modelIdList: [options.id], siteId: "" }));
  nextTick(() => {
    list.data[options.id]?.pcTplList && list.data[options.id].pcTplList.length && list.data[options.id].pcTplList.forEach((item: string) => {
      let obj = { label: item, value: item };
      formState.value.PCModel.options.push(obj);
    })
    list.data[options.id]?.mobileTplList && list.data[options.id].mobileTplList.length && list.data[options.id].mobileTplList.forEach((item: string) => {
      let obj = { label: item, value: item };
      formState.value.MobileModel.options.value.push(obj);
    })
  })
};


//获取栏目模型的选项列表
const getColumnModelLList = async () => {
  const param: {} = {
    modelType: 1,
    name: "",
    status: 1,
    type: "",
  };
  contentOptions.value = (await request.fetchColumnModelList(param)) || {};
  contentOptions.value.forEach((item: any) => {
    item.value = item.name;
  });
};
const onFocus = (id: number, type: any = null) => {
  pcTplList.value = [];
  mobileTplList.value = [];
  fetchChannelTplList(id, type);
};
//根据模型ID获取关联的模板列表
const fetchChannelTplList = async (id: number, type: any = null) => {
  const list =
    (await request.fetchChannelTplList({ modelIdList: [id], siteId: "" })) || []
  list.data[id]?.pcTplList && list.data[id].pcTplList.length && list.data[id].pcTplList.map((item: string) => {
    let obj = { label: item, value: item }
    pcTplList.value.push(obj);
    if(!type) {
      contentModelList.value.forEach((item2: any) => {
      if(id == item2.id) {
        if(!item2.tplPc) {
          item2.tplPc = item
        }
      }
    })
    }
  })
  
  list.data[id]?.mobileTplList && list.data[id].mobileTplList.length && list.data[id].mobileTplList.map((item: string) => {
    let obj = { label: item, value: item }
    mobileTplList.value.push(obj);
    if(!type) {
      contentModelList.value.forEach((item2: any) => {
      if(id == item2.id) {
        if(!item2.mobileTpl) {
          item2.mobileTpl = item
        }
      }
    })
    }
  })
  
};

//获取内容模型列表
const fetchChannelContentModelTplList = async (type?: number) => {
  const list: dataSourceType[] = await request.fetchColumnModelList({
    modelType: 2,
    status: 1,
  });
  if (!list.length) {
    Modal.confirm(
      Object.assign({}, msgModal.confirm, {
        title: "内容模型未关联模板，请前往内容模板关联模型",
        content: "",
        icon: createVNode("i", {
          class: "iconfont icon-warn warning_ICON",
        }),
        okText: "前往创建",
        cancelButtonProps: { style: { display: "none" } } as any,
        onOk: () => {
          router.push({
            path: "/config/templateManagement",
          });
        },
      })
    );
  }
  console.log(list, 'lists')
  list.length &&
    list.forEach((item: any) => {
      item.modelId = item.id;
      item.modelName = item.name;
      if (item.selected) {
        rowSelectedKey.value.push(item.id);
      }
    });
  contentModelList.value = list || [];
  const ids = contentModelList.value.map((item: any) => {
    return item.id;
  });
  fetchChannelModelTplList(ids);
};

// watch
watch(() => addModelBaseTables.value?.selectedRowKeys, (newVal: any, oldVal: any) => {
  if(newVal.length > 0){
    console.log(newVal,'newVal');
    onFocus(newVal[newVal.length - 1])
  }
});
//获取内容模型列表
const fetchChannelModelTplList = async (ids: number[]) => {
  const list =
    (await request.fetchChannelModelTplList({ modelIdList: ids, siteId: "" })) || [];

};
// 新添或编辑栏目调取接口
//保存
const buttonMessage = async (msg: dataSourceType) => {
  let selectedRowKeys = addModelBaseTables.value.selectedRowKeys || [];
  columnFrom.value
    .validate()
    .then(() => {
      const params = {
        parentId: formState.value.parentId,
        modelId: formState.value.modelId,
        channelName: formState.value.columnName.value,
        channelPath: formState.value.path.value,
        showInLoop: false,
        contentModelTplDtoList: contentModelList.value.filter((item: any) => selectedRowKeys.includes(item.id)),
        tplPc: formState.value.PCModel.value,
        tplMobile: formState.value.MobileModel.value,

      };
      request.fetchChannelAdd(params).then((res: any) => {
        if (res.code == "00000 00000") {
          message.success(res.message);
          router.push('/colunm/index')
        } else {
          message.error(res.message);
        }
      })
        .catch((err: any) => {
          throw new Error(err);
        });
      isVisible.value = false;
    })
    .catch(() => { });
};
const parentKey = ref<(string | number)[]>([]);
const getParentKey = (data: dataSourceType[]) => {
  for (let i = 0; i < data.length; i++) {
    parentKey.value.push(data[i].id);
    if (data[i].children) {
      getParentKey(data[i].children);
    }
  }
};

// 树形是否可点击工具
const deepRec = function (data: any) {
  data.forEach((item: any) => {
    if (!item.createChildPerm) {
      item.disabled = true;
    } else {
      item.disabled = false;
    }
    if (item.children && item.children.length > 0) {
      deepRec(item.children);
    }
  });
};
const disabledParent = function (data: any, id: any[]) {
  data.forEach((item: any) => {
    if (id.includes(item.id)) {
      item.disabled = true;
      item.disableCheckbox = true;
    } else if (!item.createChildPerm) {
      item.disabled = true;
      item.disableCheckbox = true;
    } else {
      item.disabled = false;
      item.disableCheckbox = false;
    }

    if (item.children && item.children.length > 0) {
      disabledParent(item.children, id);
    }
  });
};
const getModelValue = (id: number | string) => {
  let modelName: string = "";
  contentOptions.value.length &&
    contentOptions.value.forEach((item: dataSourceType) => {
      if (item.id === id) {
        modelName = item.value || "";
      }
    });

  return modelName;
};
//onmounted
onMounted(async () => {
  btnPerm.value = routerPerm();
  getColumnModelLList();
  fetchChannelChannelTree();
  fetchChannelContentModelTplList();
  useFixeWidth();
});
</script>
<style lang="less">
.createCloumn {
  width: 100%;
  height: 100%;





  .create_columnIndex {
    background: #fff;
    height: calc(100% - 122px);
    padding-left: 32px;
    padding-top: 24px;

    .columnIndex_button {
      margin-bottom: 24px;
    }

    .creatForm {
      overflow: auto;
      height: calc(100% - 96px);
      .tpllPc {
        display: flex;
        align-items: center;
        .title {
          margin-right: 5px;
        }
        .tips {
          display: inline-block;
          margin-left: 5px;
            width: 125px;
            font-size: 12px;
            color:rgba(0,0,0,.4);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
      }
      .ant-form-item {
        width: 474px;

        .ant-form-item-label {
          width: 126px;
        }
      }
      .ant-table-thead .ant-table-cell:nth-last-of-type(1) {
        text-align: left;
      }
      .ant-form-item:nth-last-of-type(1) {
        width: 874px;
      }
    }


  }

  .table-bottom_fiexd {
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 0;
    z-index: 10;
    background: #fff;
  }
}
</style>
